package com.hnevc.androiduiclassone8;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QQLoginActivity extends AppCompatActivity {

    EditText mEtNumber, mEtPassword;
    Button mBtnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qqlogin);

        initView();

        initEvent();

    }

    private void initEvent() {
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = mEtNumber.getText().toString();
                String password = mEtPassword.getText().toString();

                saveUserInfo(number, password);
            }
        });
    }

    private void saveUserInfo(String number, String password) {
        String data = number + ":" + password;
        try {
            FileOutputStream fos = openFileOutput("data.txt", MODE_PRIVATE);
            fos.write(data.getBytes());
            fos.close();
            Toast.makeText(QQLoginActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Map<String, String> getUserInfo() {
        try {
            FileInputStream fis = openFileInput("data.txt");
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            fis.close();
            String temp = new String(bytes);
            String[] strs = temp.split(":");
            Map<String, String> map = new HashMap();
            map.put("number", strs[0]);
            map.put("password", strs[1]);
            return map;
        } catch (FileNotFoundException e) {
            return null;
        } catch (IOException e) {
            return null;
        }


    }

    private void initView() {
        mEtNumber = findViewById(R.id.et_number);
        mEtPassword = findViewById(R.id.et_password);
        mBtnLogin = findViewById(R.id.btn_login);

        Map<String,String > userInfo = getUserInfo();
        if(userInfo!=null){
            mEtNumber.setText(userInfo.get("number"));
            mEtPassword.setText(userInfo.get("password"));
        }
    }
}
